<?php

class ZFileUpload {

    /**
     * 
     * 获取文件目录
     * @param unknown_type $dir
     */
    static public function getFildDir($dir) {
        $upload_dir_array = array(
            'cache' => Yii::getPathOfAlias('webroot') . "/statics/cache",
            'upload' => Yii::getPathOfAlias('webroot') . "/statics/upload",
	    'yunfiles_tmp' => Yii::getPathOfAlias('webroot') . "/statics/upload/yunfiles/tmp",
	    'yunfiles' => Yii::getPathOfAlias('webroot') . "/statics/upload/yunfiles/files",
            'module_file' => Yii::getPathOfAlias('webroot') . "/statics/upload/userfiles",
            'module_share' => Yii::getPathOfAlias('webroot') . "/statics/upload/share",
            'module_user_thumb' => Yii::getPathOfAlias('webroot') . "/statics/upload/useravater",
            'module_school_thumb' => Yii::getPathOfAlias('webroot') . "/statics/upload/schoolavater",
            'tmp_image' => Yii::getPathOfAlias('webroot') . "/statics/upload/tmp/images",
            'xls_image' => Yii::getPathOfAlias('webroot') . "/statics/upload/xlsimg",
            'group_image' => Yii::getPathOfAlias('webroot') . "/statics/upload/group",
            'module_atten'	=> Yii::getPathOfAlias('webroot') . "/statics/upload/atten",
            'module_im'	=> Yii::getPathOfAlias('webroot') . "/statics/upload/imimg",
	    'module_oa_file'	=> Yii::getPathOfAlias('webroot') . "/statics/upload/oa",
            'user_zj'	=> Yii::getPathOfAlias('webroot') . "/statics/upload/certificate"
        );
        return isset($upload_dir_array[$dir]) ? $upload_dir_array[$dir] : '';
    }


    /**
     * xls 上传头像
     * */
    static public function uploadFileInfoName($fname)
    {
       /**
         * xls上传图片
         * @wjy
         * */ 
        $res = array();
        if(!empty($fname))
        {
            $upload_path = ZFileUpload::getFildDir("tmp_image");  //得到上传路径
            $file_name_list = ZFileUpload::getUniqueID();  //得到唯一名称
            $file_name = ZFileUpload::getFildDir("xls_image");
            $file_name .= '/'.$fname;
           
            $extend = pathinfo($fname);
            $extend = strtolower($extend["extension"]);
            $file_name_list .= '.' . $extend;    //得到文件后缀

            $file_type = copy($file_name, $upload_path . '/' . $file_name_list);
            
            if ($file_type) {
                $res['success'] = 1;
                $res['type'] = $extend;
                
                $file=$upload_path."/".$file_name_list;
                $newFileName=self::xlsproAvater($file);
                
                $res['file'] = $newFileName;
                $res['url'] = STATICS_URL . "/upload/tmp/images/" . $newFileName;
                
                $size = getimagesize($res['url']);
                $res['width'] = $size[0];
                $res['height'] = $size[1];
                $res['size'] = $size[3];
            }
             
        }
        return $res;
    } 

    static public function xlsproAvater($file){
       $imgDir = self::getFildDir("tmp_image");
        $config = self::avater_crop_pic_rules(true);
        $newFileName=self::getUniqueID().".jpg";
        $newF=$imgDir."/".$newFileName; 
        foreach ($config as $value) {
            $tar_img = $newF.$value['name'];
            $dst_w = $value['w'];
            $dst_h = $value['h'];
            $result = ZCrop::thumbcrop($file, $tar_img, $dst_w, $dst_h, true, 80);
            if (!$result) {
                //记录出错信息
            }
                
        } 
        return $newFileName;
    }
    
    static public function share_crop_pic_rules($isorigin=false) {//164x164    164x310     164x155    329x155
        $config = array(
            array('name' => '_50x50.jpg', 'w' => 50, 'h' => 50),
            array('name' => '_88x88.jpg', 'w' => 88, 'h' => 88),
            array('name' => '_162x204.jpg', 'w' => 162, 'h' => 204),
            array('name' => '_132x132.jpg', 'w' => 132, 'h' => 132),
            array('name' => '_390x999.jpg', 'w' => 390, 'h' => 0),
        );
        if ($isorigin)
            $config[] = array('name' => '', 'w' => 0, 'h' => 0);
        return $config;
    }

    static public function avater_crop_pic_rules($isorigin=false) {
        $config = array(
            array('name' => '_24x24.jpg', 'w' => 24, 'h' => 24),
            array('name' => '_32x32.jpg', 'w' => 32, 'h' => 32),
            array('name' => '_64x64.jpg', 'w' => 64, 'h' => 64),
            array('name' => '_100x100.jpg', 'w' => 100, 'h' => 100),
            array('name' => '_200x200.jpg', 'w' => 200, 'h' => 200),
            array('name' => '_200x999.jpg', 'w' => 200, 'h' => 0)
        );

        if ($isorigin)
            $config[] = array('name' => '', 'w' => 0, 'h' => 0);
        return $config;
    }
    static public function topic_crop_pic_rules($isorigin=false) {
        $config = array(
            array('name' => '_487x202.jpg', 'w' => 487, 'h' => 202),
            array('name' => '_299x200.jpg', 'w' => 299, 'h' => 200),
            array('name' => '_185x200.jpg', 'w' => 185, 'h' => 200),
            array('name' => '_185x99.jpg', 'w' => 185, 'h' => 99),
            array('name' => '_81x80.jpg', 'w' => 81, 'h' => 80)
        );
        if ($isorigin)
            $config[] = array('name' => '', 'w' => 0, 'h' => 0);
        return $config;
    }
    static public function share_school_crop_pic_rules($isorigin=false) {//164x164    164x310     164x155    329x155
        $config = array(
            array('name' => '_180x122.jpg', 'w' => 182, 'h' => 122),
            array('name' => '_315x244.jpg', 'w' => 315, 'h' => 244),
            array('name' => '_175x177.jpg', 'w' => 175, 'h' => 177),
            array('name' => '_132x132.jpg', 'w' => 132, 'h' => 132),
            array('name' => '_88x88.jpg', 'w' => 88, 'h' => 88)
        );
        if ($isorigin)
            $config[] = array('name' => '', 'w' => 0, 'h' => 0);
        return $config;
    }
    /**
     * 
     * 获取唯一图片ID
     */
    static public function getUniqueID() {
        return strtolower(date("YmdHis") . '_' . uniqid() . '_' . rand(10000, 99999));
    }

    static public function getMd5UniqueId() {
        return strtolower(md5(date("YmdHis") . uniqid() . rand(10000, 99999)));
    }

    /**
     * 
     * 裁剪图片
     * @param unknown_type $src_img
     * @param unknown_type $tar_dir
     * @param unknown_type $imgname
     * @param unknown_type $ext
     * @param unknown_type $config
     */
    static public function cropImage($config, $src_img, $tar_dir, $imgname='', $ext='', $is_imgname=false,$aa_user_sn=0) {
        /*
          $config=array(
          array('name'=>'','w'=>0,'h'=>0),
          //array('name'=>'50_50_','w'=>50,'h'=>50),
          //array('name'=>'115_115_','w'=>115,'h'=>115),
          //array('name'=>'231_231_','w'=>231,'h'=>231),
          //array('name'=>'200_','w'=>200,'h'=>0),
          ); */
		  		  
        if($aa_user_sn=0)
		{
			$imgname = self::getUniqueID();	
		}else{
			$imgname = md5($aa_user_sn.date('YmdHi'));
		}
        if ($config == '')
            return false;
        if (!$is_imgname) {
            $ext = strtolower($ext);
            if ($ext != "" && in_array($ext, array('gif', 'jpg', 'png'))) {
                //$imgname = $imgname . "." . $ext;
            	$imgname = $imgname . "_200x200.jpg";
			} else {
                $ext = strtolower(strrchr($src_img, "."));
                if ($ext != ".gif" && $ext != ".jpg" && $ext != ".png")
                    return false;
                $imgname = $imgname . "_200x200.jpg";
				//$imgname = $imgname . $ext;
            }
        }
        foreach ($config as $value) {
			
            //$tar_img = $tar_dir."/".$value['name'].$imgname;
			$tar_img = $tar_dir."/".$imgname.$value['name'];
			
            $dst_w = $value['w'];
            $dst_h = $value['h'];
            Yii::import('ext.thumbcrop.Ecrop');
            $jcropper = new Ecrop();
            if ($src_img != '') {
                if (!$jcropper->thumbcrop($src_img, $tar_img, $dst_w, $dst_h)) {
                    //return false;
                }
            }
        }
        return $imgname;
    }

    /**
     * 
     * 裁剪图片
     * @param unknown_type $src_img
     * @param unknown_type $tar_dir
     * @param unknown_type $imgname
     * @param unknown_type $ext
     * @param unknown_type $config
     */
    static public function cropImageNew($config, $src_img,$isSharp=false,$quality=80) {
        /*
          $config=array(
          array('name'=>'','w'=>0,'h'=>0),
          //array('name'=>'50_50_','w'=>50,'h'=>50),
          //array('name'=>'115_115_','w'=>115,'h'=>115),
          //array('name'=>'231_231_','w'=>231,'h'=>231),
          //array('name'=>'200_','w'=>200,'h'=>0),
          ); */

        if (empty($src_img) || empty($config))
            return false;

        foreach ($config as $value) {
            $tar_img = $src_img . $value['name'];
            $dst_w = $value['w'];
            $dst_h = $value['h'];
            Yii::import('ext.thumbcrop.Ecrop');
            $jcropper = new Ecrop();
            if ($src_img != '') {
                $result=$jcropper->thumbcrop($src_img, $tar_img, $dst_w, $dst_h,$isSharp,$quality);
                if (!$result) {
                    //return false;
                }
            }
        }
        return true;
    }

    /**
     * 
     * 获取远程图片
     * @param unknown_type $url
     * @param unknown_type $imgDir
     */
    static function grabImage($url, $tar_dir, $imgname='') {
        if ($url == "")
            return false;

        $ext = strtolower(strrchr($url, "."));
        if ($ext != ".gif" && $ext != ".jpg" && $ext != ".png")
            return false;

        if ($imgname == '')
            $imgname = self::getUniqueID();

        $tar_img = $tar_dir . "/" . $imgname . $ext;
        ob_start();
        readfile($url);
        $img = ob_get_contents();
        ob_end_clean();
        $size = strlen($img);
        $fp2 = @fopen($tar_img, 'a');
        fwrite($fp2, $img);
        fclose($fp2);
        return $imgname;
    }

    static function mmkdir($pathname, $basepath = './', $mode = 0777) {
        $paths = '';
		$pathname = ltrim($pathname, '/');
        $pathname = rtrim($pathname, '/');
        $pathArray = explode('/', $pathname);
        foreach ($pathArray as $path) {
            $paths .= $path . '/';
            if ($basepath) {
                $path = $basepath . '/' . $paths;
                if (!is_dir($path)) {
                    mkdir($path, $mode);
                }
            } else {
                if (!is_dir($path)) {
                    mkdir($paths, $mode);
                }
            }
        }
        if (is_dir($basepath . $pathname)) {
            return $basepath . $pathname;
        } else {
            return FALSE;
        }
    }

    static function loadJpeg($imgname, $type) {
        if ($type == 'jpeg') {
            $im = @imagecreatefromjpeg($imgname);
        } elseif ($type == 'png') {
            $im = @imagecreatefrompng($imgname);
        } elseif ($type == 'gif') {
            $im = @imagecreatefromgif($imgname);
        } elseif ($type == 'bmp') {
            $im = @imagecreatefromwbmp($imgname);
        }

        if (!$im) { /* See if it failed */
            $im = imagecreatetruecolor(150, 30); /* Create a blank image */
            $bgc = imagecolorallocate($im, 255, 255, 255);
            $tc = imagecolorallocate($im, 0, 0, 0);
            imagefilledrectangle($im, 0, 0, 150, 30, $bgc);
            /* Output an errmsg */
            imagestring($im, 1, 5, 5, "Error loading $imgname", $tc);
        }
        return $im;
    }

    static function picmine($src_img, $dir) {
        $picInfo = getimagesize($src_img);
        
        if (isset($picInfo['mime'])) {
            $image_w = $picInfo[0];
            $image_h = $picInfo[1];
            $unique = ZFileUpload::getMd5UniqueId();
            $imgname = $unique . "_" . $image_w . "x" . $image_h . ".jpg";


            $img_dir = Func::getImageDir($imgname);
            $imgDir = ZFileUpload::getFildDir('goods') . "/tmp/newavater/" . $img_dir;


            if (!is_dir($imgDir)) {
                mkdir($imgDir, 0777, true);
            }

            $new_img = $imgDir . "/" . $imgname;


            $picmine = strtolower($picInfo['mime']);
            switch ($picmine) {
                case 'image/jpeg':
                    $image = self::loadJpeg($src_img, 'jpeg');
                    break;
                case 'image/png':
                    try {
                        $image = self::loadJpeg($src_img, 'png');
                    } catch (Exception $e) {
                        print $e->getMessage();
                        echo "<br>";
                    }
                    break;
                case 'image/gif':
                    try {
                        $image = self::loadJpeg($src_img, 'gif');
                    } catch (Exception $e) {
                        print $e->getMessage();
                        echo "<br>";
                    }
                    break;
                case 'image/x-ms-bmp':
                    try {
                        $image = self::loadJpeg($src_img, 'bmp');
                    } catch (Exception $e) {
                        print $e->getMessage();
                        echo "<br>";
                    }

                    break;

                default:
                    break;
            }

            $data['image'] = $image;
            $data['imgname'] = $imgname;
            $data['new_img'] = $new_img;
            return $data;
        }
    }

    static function uploadShareImage($src_img,$type="") {
        $picInfo = @getimagesize($src_img);
        if (isset($picInfo['mime'])) {
            $image_w = $picInfo[0];
            $image_h = $picInfo[1];
            $unique = ZFileUpload::getMd5UniqueId();
            $imgname = $unique . "_" . $image_w . "x" . $image_h . ".jpg";
            $img_dir = Func::getImageDir($imgname);
            $imgDir = ZFileUpload::getFildDir('module_share') . "/" . $img_dir;
            if (!is_dir($imgDir)) {
                mkdir($imgDir, 0777, true);
            }
            $new_img = $imgDir . "/" . $imgname;
            $result=ZCrop::thumbcrop($src_img, $new_img, 0, 0,false,100);
            if ($result) {
                if($type == 2){
                    $config=ZFileUpload::share_school_crop_pic_rules();
                }else{
                    $config=ZFileUpload::share_crop_pic_rules();
                }
                foreach ($config as $value) {
                    $tar_img = $new_img . $value['name'];
                    $dst_w = $value['w'];
                    $dst_h = $value['h'];
                    if ($src_img != '') {        
                        $res=ZCrop::thumbcrop($new_img, $tar_img, $dst_w, $dst_h,true,80);
                       
                        if (!$res) {
                            //记录出错信息
                        }
                    }
                }
            }
            return $img_dir . "/" . $imgname;
        }
    }

     static function uploadShareSchoolImage($src_img) {
echo $src_img;die;
        $picInfo = @getimagesize($src_img);
        if (isset($picInfo['mime'])) {
            $image_w = $picInfo[0];
            $image_h = $picInfo[1];
            $unique = ZFileUpload::getMd5UniqueId();
            $imgname = $unique . "_" . $image_w . "x" . $image_h . ".jpg";
            $img_dir = Func::getImageDir($imgname);
            $imgDir = ZFileUpload::getFildDir('module_share') . "/" . $img_dir;
            if (!is_dir($imgDir)) {
                mkdir($imgDir, 0777, true);
            }

            $new_img = $imgDir . "/" . $imgname;
            $result=ZCrop::thumbcrop($src_img, $new_img, 0, 0,false,100);
            if ($result) {
                $config=ZFileUpload::share_crop_pic_rules();
                foreach ($config as $value) {
                    $tar_img = $new_img . $value['name'];
                    $dst_w = $value['w'];
                    $dst_h = $value['h'];
                    if ($src_img != '') {        
                        $res=ZCrop::thumbcrop($new_img, $tar_img, $dst_w, $dst_h,true,80);
                       
                        if (!$res) {
                            //记录出错信息
                        }
                    }
                }
            }
            return $img_dir . "/" . $imgname;
        }
    }   
    
    
	/**
	 *  截取当前用户得打相应路径
	 *  @author wangjy
	 */
	static function uploadpath($user_sno)
	{
		$path = '';
		$user_sno_len = strlen($user_sno);
		if($user_sno_len<6)
		{
			$path_zero = '';	
			for($i=$user_sno_len;$i<6;$i++)
			{
				$path_zero .= 0;	
			}
			$user_sno = $path_zero.$user_sno;
		}
		$path1 = substr($user_sno,0,3);
		$path2 = substr($user_sno,3,3);
		return $path1.'/'.$path2.'/'.$user_sno;
	}


}